import React from 'react';
import { Card, Table, Button, Form, Input, Space, Modal, Pagination, Select, Tooltip, message } from 'antd';
import dayjs from 'dayjs';

// 设备广告（模仿 admin-web 的 MachineAdvertGroup.vue）
export default function MachineAdvertGroup() {
  // 搜索
  const [searchForm] = Form.useForm();
  const [search, setSearch] = React.useState({ userName: '', adTeamName: '', userEquipmentTeamName: '' });

  // 字典与下拉（模拟）
  const [showType] = React.useState([
    { label: '全部设备', value: 0 },
    { label: '首页轮播', value: 1 },
    { label: '详情页顶部', value: 2 },
    { label: '底部Banner', value: 3 },
  ]);
  const [advertGroupList] = React.useState([
    { id: 1, name: '节日活动组' },
    { id: 2, name: '品牌宣传组' },
    { id: 3, name: '新品推广组' },
  ]);
  const [userMachineGroupList] = React.useState([
    { id: 11, name: '华东-设备组A' },
    { id: 12, name: '华北-设备组B' },
    { id: 13, name: '华南-设备组C' },
  ]);

  // 列表与分页
  const [loading, setLoading] = React.useState(false);
  const [pageIndex, setPageIndex] = React.useState(1);
  const [pageSize, setPageSize] = React.useState(10);
  const [machineAdvertGroupList, setMachineAdvertGroupList] = React.useState(() => ([
    { id: 1001, userName: 'Alice', adTeamId: 1, adTeamName: '节日活动组', userEquipmentTeamId: 11, userEquipmentTeamName: '华东-设备组A', notes: '国庆档期', createTime: '2025-09-20 12:00' },
    { id: 1002, userName: 'Bob', adTeamId: 2, adTeamName: '品牌宣传组', userEquipmentTeamId: 12, userEquipmentTeamName: '华北-设备组B', notes: '品牌宣传投放', createTime: '2025-09-22 09:30' },
  ]));

  const filtered = React.useMemo(() => {
    let list = machineAdvertGroupList;
    if (search.userName) list = list.filter(i => String(i.userName || '').includes(search.userName));
    if (search.adTeamName) list = list.filter(i => String(i.adTeamName || '').includes(search.adTeamName));
    if (search.userEquipmentTeamName) list = list.filter(i => String(i.userEquipmentTeamName || '').includes(search.userEquipmentTeamName));
    return list;
  }, [machineAdvertGroupList, search]);

  const pageData = React.useMemo(() => {
    const start = (pageIndex - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, pageIndex, pageSize]);

  // 新增/编辑
  const [dialogMachineAdvertGroup, setDialogMachineAdvertGroup] = React.useState(false);
  const [groupForm] = Form.useForm();
  const [editingRow, setEditingRow] = React.useState(null);

  const addMachineAdvertGroup = () => {
    setEditingRow(null);
    groupForm.resetFields();
    setDialogMachineAdvertGroup(true);
  };
  const editMachineAdvertGroup = (row) => {
    setEditingRow(row);
    setDialogMachineAdvertGroup(true);
    groupForm.setFieldsValue({
      adTeamId: row.adTeamId,
      userEquipmentTeamId: row.userEquipmentTeamId,
      notes: row.notes,
    });
  };
  const saveMachineAdvertGroup = async () => {
    const values = await groupForm.validateFields();
    const adTeam = advertGroupList.find(a => a.id === values.adTeamId);
    const team = userMachineGroupList.find(t => t.id === values.userEquipmentTeamId);
    if (editingRow) {
      setMachineAdvertGroupList(prev => prev.map(i => (i.id === editingRow.id ? {
        ...i,
        adTeamId: values.adTeamId,
        adTeamName: adTeam?.name || '',
        userEquipmentTeamId: values.userEquipmentTeamId,
        userEquipmentTeamName: team?.name || '',
        notes: values.notes,
      } : i)));
      message.success('设备广告已更新');
    } else {
      const id = Math.max(0, ...machineAdvertGroupList.map(i => i.id)) + 1;
      const newItem = {
        id,
        userName: 'Admin',
        adTeamId: values.adTeamId,
        adTeamName: adTeam?.name || '',
        userEquipmentTeamId: values.userEquipmentTeamId,
        userEquipmentTeamName: team?.name || '',
        notes: values.notes || '',
        createTime: dayjs().format('YYYY-MM-DD HH:mm'),
      };
      setMachineAdvertGroupList(prev => [newItem, ...prev]);
      message.success('设备广告已添加');
    }
    setDialogMachineAdvertGroup(false);
  };

  // 关联弹窗：查看广告分组列表
  const [dialogAdvertGroup, setDialogAdvertGroup] = React.useState(false);
  const [adTeamId, setAdTeamId] = React.useState();
  const advertGroup = (id) => {
    setAdTeamId(id);
    setDialogAdvertGroup(true);
  };

  // 关联弹窗：查看设备组列表
  const [dialogUserMachineGroup, setDialogUserMachineGroup] = React.useState(false);
  const [teamId, setTeamId] = React.useState();
  const userMachineGroup = (id) => {
    setTeamId(id);
    setDialogUserMachineGroup(true);
  };

  const deleteMachineAdvertGroup = (row) => {
    Modal.confirm({
      title: '删除确认',
      content: `确定删除设备广告「${row.adTeamName} - ${row.userEquipmentTeamName}」吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setMachineAdvertGroupList(prev => prev.filter(i => i.id !== row.id));
        message.success('删除成功');
      },
    });
  };

  const onSubmitSearch = async () => {
    const values = await searchForm.validateFields();
    setSearch(values);
    setPageIndex(1);
  };
  const resetSearch = () => {
    searchForm.resetFields();
    setSearch({ userName: '', adTeamName: '', userEquipmentTeamName: '' });
    setPageIndex(1);
  };

  const columns = [
    { title: '用户昵称', dataIndex: 'userName', width: 250, align: 'center' },
    {
      title: '广告分组', dataIndex: 'adTeamName', width: 250, align: 'center',
      render: (text, row) => (
        <Tooltip title="点击查看广告分组列表">
          <Button type="link" onClick={() => advertGroup(row.adTeamId)}>{text}</Button>
        </Tooltip>
      )
    },
    {
      title: '设备分组', dataIndex: 'userEquipmentTeamName', width: 250, align: 'center',
      render: (text, row) => (
        <Tooltip title="点击查看设备分组列表">
          <Button type="link" onClick={() => userMachineGroup(row.userEquipmentTeamId)}>{text}</Button>
        </Tooltip>
      )
    },
    { title: '备注', dataIndex: 'notes', align: 'center' },
    { title: '创建时间', dataIndex: 'createTime', width: 160, align: 'center' },
    {
      title: '操作', fixed: 'right', width: 155, align: 'center',
      render: (_, row) => (
        <Space>
          <Button size="small" onClick={() => editMachineAdvertGroup(row)}>编辑</Button>
          <Button size="small" danger onClick={() => deleteMachineAdvertGroup(row)}>删除</Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="machine-advert-group">
      {/* 搜索与新增 */}
      <div className="el-search vue-top-padding" style={{ marginBottom: 12 }}>
        <div className="el-left" style={{ display: 'inline-block' }}>
          <Button type="primary" onClick={addMachineAdvertGroup}>新增设备广告</Button>
        </div>
        <div className="el-right" style={{ float: 'right' }}>
          <Form form={searchForm} layout="inline" initialValues={search}>
            <Form.Item name="userName">
              <Input placeholder="用户昵称" allowClear />
            </Form.Item>
            <Form.Item name="adTeamName">
              <Input placeholder="广告分组名称" allowClear />
            </Form.Item>
            <Form.Item name="userEquipmentTeamName">
              <Input placeholder="设备分组名称" allowClear />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" onClick={onSubmitSearch}>搜索</Button>
                <Button onClick={resetSearch}>重置</Button>
              </Space>
            </Form.Item>
          </Form>
        </div>
      </div>

      {/* 表格 */}
      <Card className="vue-padding radius">
        <Table
          rowKey={(r) => r.id}
          loading={loading}
          dataSource={pageData}
          columns={columns}
          pagination={false}
          scroll={{ y: 638 }}
          bordered
        />

        <div style={{ marginTop: 12, display: 'flex', justifyContent: 'center' }}>
          <Pagination
            current={pageIndex}
            pageSize={pageSize}
            total={filtered.length}
            showSizeChanger
            onChange={(pi, ps) => { setPageIndex(pi); setPageSize(ps); }}
          />
        </div>
      </Card>

      {/* 新增/编辑设备广告 */}
      <Modal
        title={editingRow ? '编辑设备广告' : '新增设备广告'}
        open={dialogMachineAdvertGroup}
        onCancel={() => setDialogMachineAdvertGroup(false)}
        onOk={saveMachineAdvertGroup}
        okText="保存"
        cancelText="取消"
      >
        <Form form={groupForm} layout="vertical">
          <Form.Item label="广告分组" name="adTeamId" rules={[{ required: true, message: '请选择广告分组' }]}> 
            <Select options={advertGroupList.map(a => ({ label: a.name, value: a.id }))} placeholder="请选择广告分组" />
          </Form.Item>
          <Form.Item label="设备分组" name="userEquipmentTeamId" rules={[{ required: true, message: '请选择设备分组' }]}> 
            <Select options={userMachineGroupList.map(t => ({ label: t.name, value: t.id }))} placeholder="请选择设备分组" />
          </Form.Item>
          <Form.Item label="备注" name="notes"> 
            <Input.TextArea rows={3} placeholder="备注" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 关联弹窗：广告分组列表 */}
      <Modal
        title="广告分组列表"
        open={dialogAdvertGroup}
        onCancel={() => setDialogAdvertGroup(false)}
        footer={null}
        width={600}
      >
        <Table
          rowKey={(r) => r.id}
          dataSource={advertGroupList}
          columns={[{ title: 'ID', dataIndex: 'id', width: 80 }, { title: '分组名称', dataIndex: 'name' }]}
          pagination={false}
        />
      </Modal>

      {/* 关联弹窗：设备分组列表 */}
      <Modal
        title="设备分组列表"
        open={dialogUserMachineGroup}
        onCancel={() => setDialogUserMachineGroup(false)}
        footer={null}
        width={600}
      >
        <Table
          rowKey={(r) => r.id}
          dataSource={userMachineGroupList}
          columns={[{ title: 'ID', dataIndex: 'id', width: 80 }, { title: '分组名称', dataIndex: 'name' }]}
          pagination={false}
        />
      </Modal>
    </div>
  );
}